# -*- coding:utf-8 -*-

import web

#from google.appengine.api import users
#from google.appengine.ext import webapp
#from google.appengine.ext.webapp.util import run_wsgi_app
#from google.appengine.ext.webapp import template

#使用mako模板
from web.contrib.template import render_mako

from google.appengine.ext import db

from conf import Fetion
from dbEntity import *
from weather import Weather
from PyFetion import *

urls = ( '/', 'index',
        '/init', 'InitAdmin',
        '/login', 'Login',
        '/logout', 'Logout',
        '/admin', 'Admin',
        '/donew', 'DoNew',
        '/petition', 'Petition',
        '/addnew', 'AddNew',
        '/deluser', 'DelUser',
        '/addtarget', 'AddTarget',
        '/deltarget', 'DelTarget',
        '/addcity', 'AddCity',
        '/delcity', 'DelCity',
        '/send-msg-to-phone-by-pyfetion', 'Send',
        )

web.config.debug = True
app = web.application(urls, globals())

#render = web.template.render("templates/")  # 使用自带模板系统
## 使用Mako模板
render = render_mako(
            directories=['templates'],
            input_encoding='utf-8',
            output_encoding='utf-8',
         )


## 全局方法
def get_max_id(tableClass, idcol):
    # 获取table的最大id值
    try:
        cur_id = db.GqlQuery("select max(%s) from %s" % (idcol, tableClass))
        return int(cur_id)
    except:
        return 0


## 页面实例
class index:
    """首页"""
    def GET(self):
        citys = City.all().fetch(10)
        return render.index(citys=citys)


class InitAdmin:
    """初始化管理员，添加用户和密码。用于gae调试。"""
    def GET(self):
        admin = AdminUser(
                            username="admin",
			                pwd = "xiaoping"
                         )
        db.put(admin)
        raise web.seeother('/admin')


class Login:
    """登录后台"""
    def GET(self):
        return render.login()

    def POST(self):
        username, pwd = web.input().user, web.input().pwd

#        result = list(db.query("select * from admin where username=$name and pwd=$pwd",
#            vars = {"name": username, "pwd": pwd}))
        result = AdminUser.gql("WHERE username=:1 AND pwd=:2",
                                username, pwd).fetch(1)

        if result:
            raise web.seeother('/admin')
        else:
            raise web.seeother('/')


class Logout:
    """退出管理后台"""
    def GET(self):
        raise web.seeother('/')

class Admin:
    """管理后台"""
    def GET(self):
        newers = list(NewUser.gql("LIMIT 50"))
        users = list(User.gql("LIMIT 50"))
        citys = list(City.gql("LIMIT 50"))
        targets = list(Target.gql("LIMIT 50"))

        return render.admin(newers=newers,
                            users=users,
                            citys=citys,
                            targets=targets
                            )


class Petition:
    """首页用户提交申请"""
    def POST(self):
        try:
            phone,city,msg = web.input().phone,web.input().city,web.input().msg
            newer = NewUser(
                            id = get_max_id("NewUser","id") + 1,
                            phone=phone,
                            city=city,
                            msg=msg
                           )

            db.put(newer)
            raise web.seeother('/')

        except:
            return 'error...'


class DoNew:
    """处理首页用户的申请，目前还没有实现全自动的处理.
       这中间涉及到添加飞信好友、添加用户信息、添加发送目标信息等。
       目前的方式是看到申请后手动进行上面的申请操作，然后这里删除用户的申请信息。
    """
    def GET(self):
        try:
            #db.delete("newuser", where="id=$id", vars={"id": web.input().id})
            id = web.input().id
            result = db.GqlQuery("SELECT * FROM NewUser WHERE id=:1", id).fetch(1)
            db.delete(result)

            raise web.seeother('/admin')
        except:
            return 'error...'


class AddNew:
    """添加正式订阅的用户信息"""
    def POST(self):
        i = web.input()
        sip,nick,cell,city = i.sip,i.nick,i.cell,i.city
        try:
            user = User(
                        userid = get_max_id("User","userid") + 1,
                        fetionsip=sip,
                        nickname=nick,
                        cellphone=cell
                       )
            user.put()
            target = Target(sip=sip, city=city)
            target.put()

            raise web.seeother('/admin')
        except:
            return "error..."


class DelUser:
    """删除已订阅的用户，如果要取消发送消息需要先删除订阅城市信息再删用户"""
    def GET(self):
        try:
            userid = web.input().id
            #db.delete('user', where="userid=$userid", vars={'userid':userid})
            result = db.GqlQuery("SELECT * FROM User WHERE userid = :1", userid).fetch(1)
            db.delete(result)

            raise web.seeother('/admin')
        except:
            return "error..."


class AddTarget:
    """添加用户订阅的目标城市"""
    def GET(self):
        try:
            fetionsip = web.input().sip
            #citys = list(db.select("city"))
            citys = list(City.gql("LIMIT 50"))
            return render.addtarget(fetionsip=fetionsip, citys=citys)
        except:
            return "error..."

    def POST(self):
        try:
            sip,city = web.input().sip, web.input().city
            #db.insert("target", sip=sip, city=city)
            target = Target(sip=sip, city=city)
            target.put()

            raise web.seeother('/admin')
        except:
            return "error..."


class DelTarget:
    """删除用户订阅的目标城市"""
    def GET(self):
        sip,city = web.input().sip, web.input().city
        #db.delete("target", where="sip=$sip and city=$city", vars={"sip":sip, "city":city})
        result = db.GqlQuery("SELECT * FROM Target WHERE sip =:1 AND city=:2", sip, city).fetch(1)
        db.delete(result)

        raise web.seeother('/admin')


class AddCity:
    """添加城市信息"""
    def POST(self):
        cityname, uri = web.input().cityname, web.input().uri
        #db.insert("city", cityname=cityname, uri=uri)
        city = City(cityname=cityname, uri=uri)
        city.put()

        raise web.seeother('/admin')


class DelCity:
    """删除多余的城市信息"""
    def GET(self):
        cityid = web.input().id
        #db.delete("city", where="cityid=$cityid", vars={"cityid":cityid})
        result = db.GqlQuery("SELECT * FROM City WHERE cityid=:1", cityid).fetch(1)
        db.delete(result)

        raise web.seeother('/admin')


class Send:
    """Cron Task"""
    def GET(self):
        fetion = PyFetion(Fetion.fetion_id, Fetion.fetion_pwd, "HTTP")
        fetion.login(FetionHidden)

        #users = list(db.select("user"))  # 先按顺序抓取用户信息获取飞信号
        users = list(User.gql("LIMIT 50"))

        for user in users:
            sip = user.fetionsip

            #targets = list(db.select("target", where="sip=$sip", vars={"sip":sip}))  # 获取该用户订阅的城市
            targets = list(
                           Target.gql("WHERE sip=:1", sip)
                          )

            outlet = ["天气预报"]  # 格式化输出内容
            for target in targets:
                city = target.city

                # 获取目标城市对应的信息源地址
                #urls = list(db.select("city", where="cityname=$city", vars={"city":city}))
                urls = list(
                            City.gql("WHERE cityname=:1", city)
                           )

                city = city.encode('utf-8','ignore')
                uri = urls[0].uri

                # 抓取天气信息
                weapho = Weather(city, uri)
                outlet.append(weapho.GetWeather())

            message = "\n".join(outlet)
            fetion.send_sms(message, sip, True)
            print message

        fetion.logout()
        return "Done."

if __name__ == "__main__":
    app.cgirun()
